/**
 * @file main.c
 * @author your name (you@domain.com)
 * @brief
 * @version 0.1
 * @date 2024-01-23
 *
 * @copyright Copyright (c) 2024
 *
*/
#include <FreeRTOS.h>
#include "task.h"
#include "queue.h"
#include "board.h"
#include "bl616_glb.h"
#include "mem.h"
#include "log.h"

//lvgl
#include "lv_conf.h"
#include "lvgl.h"
#include "lv_port_disp.h"
#include "lv_port_indev.h"

//GuiGuider UI
#include "lv_user_config.h"
#include "gui_guider.h"
#include "events_init.h"
#include "custom.h"

//custom
#include "encoder.h"

#include "qyq_triled_drive.h"
#include "homeAssistantPort.h"
#include "device_ctrl.h"
#include "cJSON.h"
#define DBG_TAG "MAIN"

lv_ui guider_ui;
static homeAssisatnt_device_t ha_device;
bool mqtt_connect_status = false;
extern bool mode1_is_Suspend;
extern bool mode2_is_Suspend;
extern bool mode3_is_Suspend;
extern xTaskHandle mode1_task_handle;
extern xTaskHandle mode2_task_handle;
extern xTaskHandle mode3_task_handle;
extern xTaskHandle mode_task_handle;
/**************************************/
static int bl61x_get_heap_size(void)
{
    struct meminfo info1 = { 0 };
    struct meminfo info2 = { 0 };
    uint32_t total_free_size = 0;
    // return xPortGetFreeHeapSize();

    bflb_mem_usage(KMEM_HEAP, &info1);
    bflb_mem_usage(PMEM_HEAP, &info2);

    total_free_size = info1.free_size;
    LOG_F("heap size  KMEM heap=%d   PMEM heap=%d", info1.free_size, info2.free_size);
    return total_free_size;
}

static void bl61x_show_heap_size_task(void* arg)
{
    while (1) {
        bl61x_get_heap_size();
        vTaskDelay(3000/portTICK_PERIOD_MS);
    }
}

static uint8_t json_get_leds(const char* cjson_data, uint16_t data_len, qyq_triled_control_block_t* led_block)
{
    if (cjson_data==NULL||led_block==NULL) {
        LOG_E("params is NULL");
        return 0;
    }
    char* data = malloc(128);
    memset(data, 0, 128);
    memcpy(data, cjson_data, data_len);
    cJSON* root = cJSON_Parse(data);
    if (root==NULL)
    {
        LOG_E("This't Not json data with [%s]", data);
        return 0;
    }
    cJSON* led_id = cJSON_GetObjectItem(root, "id");
    cJSON* led_state = cJSON_GetObjectItem(root, "state");

    cJSON* led_color_r = cJSON_GetObjectItem(root, "red");
    cJSON* led_color_g = cJSON_GetObjectItem(root, "greem");
    cJSON* led_color_b = cJSON_GetObjectItem(root, "blue");

    led_block->status = led_state->valueint;
    led_block->red = led_color_r->valueint;
    led_block->green = led_color_g->valueint;
    led_block->blue = led_color_b->valueint;
    uint8_t id = led_id->valueint;
    cJSON_Delete(root);
    free(data);
    return id;
}

static  ha_event_cb(ha_event_t event, homeAssisatnt_device_t* ha_dev)
{
    switch (event)
    {
        /*  连接服务器事件  */
        case HA_EVENT_MQTT_CONNECED:
            HA_LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_CONNECED\r\n");
            mqtt_connect_status = true;
            static ha_lh_entity_t triled_all_light = {
                .name = "All",
                 .rgb.rgb_command_topic = "knob/rbg/set",
                .rgb.rgb_state_topic = "knob/rgb/state",
                .brightness.brightness_command_topic = "knob/brightness/set",
                .brightness.brightness_state_topic = "knob/brightness/state",
                .command_topic = "knob/set",
                .state_topic = "knob/state",
                .unique_id = "triled-all_01",
            };

            static ha_sw_entity_t triled_mode1_switch = {
               .name = "mode1",
               .icon = "mdi:auto-mode",
               .unique_id = "triled-mode1_01",
            };
            static ha_sw_entity_t triled_mode2_switch = {
               .name = "mode2",
               .icon = "mdi:auto-mode",
               .unique_id = "triled-mode2_01",
            };
            static ha_sw_entity_t triled_mode3_switch = {
               .name = "mode3",
               .icon = "mdi:auto-mode",
               .unique_id = "triled-mode3_01",
            };
            homeAssistant_device_add_entity(CONFIG_HA_ENTITY_LIGHT, &triled_all_light);
            homeAssistant_device_add_entity(CONFIG_HA_ENTITY_SWITCH, &triled_mode1_switch);
            homeAssistant_device_add_entity(CONFIG_HA_ENTITY_SWITCH, &triled_mode2_switch);
            homeAssistant_device_add_entity(CONFIG_HA_ENTITY_SWITCH, &triled_mode3_switch);
            homeAssistant_device_send_status(HOMEASSISTANT_STATUS_ONLINE);

            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, &triled_mode3_switch, 0);
            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, &triled_mode2_switch, 0);
            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, &triled_mode1_switch, 0);
            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_LIGHT, &triled_all_light, 0);
            homeAssistant_mqtt_port_subscribe("rgb/one/set", 0);
            break;
            /*  服务器断开事件  */
        case HA_EVENT_MQTT_DISCONNECT:
            HA_LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_DISCONNECT\r\n");
            mqtt_connect_status = false;
            break;
        case HA_EVENT_MQTT_COMMAND_SWITCH:
        {
            HA_LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_COMMAND_SWITCH\r\n");
            /* 判断 是否处于模式设置页面 如果不是，跳转到模式设置页面 */
            switch (guider_ui.screen)
            {
                case 0: //处于主页
                {
                    lv_event_send(guider_ui.main_cont_3, LV_EVENT_CLICKED, &guider_ui);//加载模式页面
                }
                break;
                case 1://处于RGB设置页面
                {
                    /* 退出当前页面*/
                    lv_event_send(guider_ui.RGB, LV_EVENT_LONG_PRESSED, &guider_ui);
                    /* 延时等待页面退出*/
                    vTaskDelay(pdMS_TO_TICKS(300));
                    /*加载模式页面*/
                    lv_event_send(guider_ui.main_cont_3, LV_EVENT_CLICKED, &guider_ui);//加载模式页面
                }
                break;
                case 2://处于数量设置页面
                {
                    /* 退出当前页面*/
                    lv_event_send(guider_ui.Quantity, LV_EVENT_LONG_PRESSED, &guider_ui);
                    /* 延时等待页面退出*/
                    vTaskDelay(pdMS_TO_TICKS(300));
                    /*加载模式页面*/
                    lv_event_send(guider_ui.main_cont_3, LV_EVENT_CLICKED, &guider_ui);//加载模式页面
                }
                break;
                default:
                    break;
            }

            ha_sw_entity_t* mode1_sw = homeAssistant_fine_entity(CONFIG_HA_ENTITY_SWITCH, "triled-mode1_01");
            ha_sw_entity_t* mode2_sw = homeAssistant_fine_entity(CONFIG_HA_ENTITY_SWITCH, "triled-mode2_01");
            ha_sw_entity_t* mode3_sw = homeAssistant_fine_entity(CONFIG_HA_ENTITY_SWITCH, "triled-mode3_01");

            if (ha_dev->entity_switch->command_switch->unique_id=="triled-mode1_01") {
                /* 滚动到模式1*/
                lv_obj_set_element_id(guider_ui.mode_carousel_1, 0, LV_ANIM_ON);
                homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, ha_dev->entity_switch->command_switch, ha_dev->entity_switch->command_switch->switch_state);
                homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, mode2_sw, 0);
                homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, mode3_sw, 0);
                HA_LOG_I("%s is %s\r\n", ha_dev->entity_switch->command_switch->name, ha_dev->entity_switch->command_switch->switch_state?"ON":"OFF");
                if (ha_dev->entity_switch->command_switch->switch_state)
                {
                    qyq_triled_drive_turn_onall();
                    triled_drive_set_mode(0);
                }
                else
                    qyq_triled_drive_turn_offall();
            }

            if (ha_dev->entity_switch->command_switch->unique_id=="triled-mode2_01") {
                /* 滚动到模式2*/
                lv_obj_set_element_id(guider_ui.mode_carousel_1, 1, LV_ANIM_ON);
                homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, ha_dev->entity_switch->command_switch, ha_dev->entity_switch->command_switch->switch_state);
                HA_LOG_I("%s is %s\r\n", ha_dev->entity_switch->command_switch->name, ha_dev->entity_switch->command_switch->switch_state?"ON":"OFF");
                homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, mode1_sw, 0);
                homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, mode3_sw, 0);

                if (ha_dev->entity_switch->command_switch->switch_state) {
                    qyq_triled_drive_turn_onall();
                    triled_drive_set_mode(1);
                }
                else
                    qyq_triled_drive_turn_offall();
            }

            if (ha_dev->entity_switch->command_switch->unique_id=="triled-mode3_01") {
                /* 滚动到模式3*/
                lv_obj_set_element_id(guider_ui.mode_carousel_1, 2, LV_ANIM_ON);
                homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, ha_dev->entity_switch->command_switch, ha_dev->entity_switch->command_switch->switch_state);
                HA_LOG_I("%s is %s\r\n", ha_dev->entity_switch->command_switch->name, ha_dev->entity_switch->command_switch->switch_state?"ON":"OFF");
                homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, mode1_sw, 0);
                homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, mode2_sw, 0);

                if (ha_dev->entity_switch->command_switch->switch_state) {
                    qyq_triled_drive_turn_onall();
                    triled_drive_set_mode(2);
                }
                else
                    qyq_triled_drive_turn_offall();
            }
        }
        break;
        case HA_EVENT_MQTT_COMMAND_LIGHT_SWITCH:
        {
            HA_LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_COMMAND_LIGHT_SWITCH\r\n");

            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_LIGHT, ha_dev->entity_light->command_light, ha_dev->entity_light->command_light->light_state);

            if (ha_dev->entity_light->command_light->unique_id=="triled-all_01") {
                HA_LOG_I("%s is %s\r\n", ha_dev->entity_light->command_light->name, ha_dev->entity_light->command_light->light_state?"ON":"OFF");
                if (ha_dev->entity_light->command_light->light_state)
                {
                    if (guider_ui.screen==0)
                        qyq_triled_drive_set_allcolor(0, 0, 0);
                    qyq_triled_drive_turn_onall();
                }
                else {
                    if (guider_ui.screen==0)
                        qyq_triled_drive_set_allcolor(0, 0, 0);
                    else {
                        qyq_triled_drive_turn_offall();
                        /* 退回到主页*/
                        switch (guider_ui.screen)
                        {
                            case 1:
                                /* code */
                                lv_event_send(guider_ui.RGB, LV_EVENT_LONG_PRESSED, &guider_ui);
                                qyq_triled_drive_set_allcolor(0, 0, 0);
                                break;
                            case 2:
                                lv_event_send(guider_ui.Quantity, LV_EVENT_LONG_PRESSED, &guider_ui);
                                qyq_triled_drive_set_allcolor(0, 0, 0);
                                break;
                            case 3:
                                /* code */
                                lv_event_send(guider_ui.mode, LV_EVENT_LONG_PRESSED, &guider_ui);
                                if (mode1_task_handle!=NULL)
                                    vTaskDelete(mode1_task_handle);
                                if (mode2_task_handle!=NULL)
                                    vTaskDelete(mode2_task_handle);
                                if (mode3_task_handle!=NULL)
                                    vTaskDelete(mode3_task_handle);
                                vTaskDelete(mode_task_handle);
                                break;
                            default:
                                break;
                        }
                    }

                }
            }
        }
        break;
        case HA_EVENT_MQTT_COMMAND_LIGHT_RGB_UPDATE:
        {
            HA_LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_COMMAND_LIGHT_RGB_UPDATE\r\n");
            ha_lh_entity_t* light_rgb = homeAssistant_fine_entity(CONFIG_HA_ENTITY_LIGHT, "triled-all_01");
            red = light_rgb->rgb.red;
            green = light_rgb->rgb.green;
            blue = light_rgb->rgb.blue;
            ha_sw_entity_t* mode1_sw = homeAssistant_fine_entity(CONFIG_HA_ENTITY_SWITCH, "triled-mode1_01");
            ha_sw_entity_t* mode2_sw = homeAssistant_fine_entity(CONFIG_HA_ENTITY_SWITCH, "triled-mode2_01");
            ha_sw_entity_t* mode3_sw = homeAssistant_fine_entity(CONFIG_HA_ENTITY_SWITCH, "triled-mode3_01");
            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, mode1_sw, 0);
            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, mode2_sw, 0);
            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, mode3_sw, 0);
            switch (guider_ui.screen)
            {
                case 0: //处于主页
                {
                    lv_event_send(guider_ui.main_cont_1, LV_EVENT_CLICKED, &guider_ui);//加载模式页面
                }
                break;
                case 3://处于模式设置页面
                {
                    /* 退出当前页面*/
                    lv_event_send(guider_ui.mode, LV_EVENT_LONG_PRESSED, &guider_ui);
                    vTaskDelay(pdMS_TO_TICKS(300));
                    /* 挂起并删除所有运行任务 */
                    if (!mode1_is_Suspend)
                    {
                        vTaskSuspend(mode1_task_handle);
                        vTaskDelete(mode1_task_handle);
                    }
                    if (!mode2_is_Suspend)
                    {
                        vTaskSuspend(mode2_task_handle);
                        vTaskDelete(mode2_task_handle);
                    }
                    if (!mode3_is_Suspend)
                    {
                        vTaskSuspend(mode3_task_handle);
                        vTaskDelete(mode3_task_handle);
                    }
                    qyq_triled_drive_turn_offall();
                    vTaskDelete(mode_task_handle);
                    /*加载模式页面*/
                    lv_event_send(guider_ui.main_cont_1, LV_EVENT_CLICKED, &guider_ui);//加载模式页面
                }
                break;
                case 2://处于数量设置页面
                {
                    /* 退出当前页面*/
                    lv_event_send(guider_ui.Quantity, LV_EVENT_LONG_PRESSED, &guider_ui);
                    vTaskDelay(pdMS_TO_TICKS(300));
                    /*加载模式页面*/
                    lv_event_send(guider_ui.main_cont_1, LV_EVENT_CLICKED, &guider_ui);//加载模式页面
                }
                break;
                default:
                    break;
            }
            lv_color_hsv_t c_hsv = lv_color_rgb_to_hsv(red, green, blue);
            c_hsv.v = 30;
            lv_colorwheel_set_hsv(guider_ui.RGB_cpicker_1, c_hsv);
            lv_color_t c = lv_color_hsv_to_rgb(c_hsv.h, c_hsv.s, c_hsv.v);
            qyq_triled_drive_set_allcolor(LV_COLOR_GET_R(c), LV_COLOR_GET_G(c), LV_COLOR_GET_B(c));
        }
        break;
        /* 自定义订阅数据的数据接收事件*/
        case HA_EVENT_MQTT_CUSTOM_SUBSCRIBE_DATA:
        {
            LOG_I("topic=%.*s,data=%.*s", ha_dev->custom_sub_data.custom_sub_topic_len, ha_dev->custom_sub_data.custom_sub_topic, ha_dev->custom_sub_data.custom_sub_data_len, ha_dev->custom_sub_data.custom_sub_data);
            /* 判断Topic */
            if (strncmp(ha_dev->custom_sub_data.custom_sub_topic, "rgb/one/set", ha_dev->custom_sub_data.custom_sub_topic_len)==0) {
                /* 解析JSON 数据，提示灯珠的ID、状态和颜色 */
                //{"id":28,"state":1,"red":0,"greem":0,"blue":255}
                if (guider_ui.screen==0) {
                    qyq_triled_control_block_t  led_block;
                    uint8_t id = json_get_leds(ha_dev->custom_sub_data.custom_sub_data, ha_dev->custom_sub_data.custom_sub_data_len, &led_block);
                    {
                        if (led_block.status) {
                            lv_color_hsv_t c_hsv = lv_color_rgb_to_hsv(led_block.red, led_block.green, led_block.blue);
                            c_hsv.v = 30;
                            lv_color_t c = lv_color_hsv_to_rgb(c_hsv.h, c_hsv.s, c_hsv.v);
                            qyq_triled_drive_set_color(id, LV_COLOR_GET_R(c), LV_COLOR_GET_G(c), LV_COLOR_GET_B(c));
                        }
                        else {
                            qyq_triled_drive_set_color(id, 0, 0, 0);
                        }

                    }
                }
            }
        }

        break;
        case HA_EVENT_MQTT_COMMAND_LIGHT_BRIGHTNESS:
        {
            HA_LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_COMMAND_LIGHT_BRIGHTNESS\r\n");
        }
        break;
        case HA_EVENT_MQTT_ERROR:
            HA_LOG_E("<<<<<<<<<<  HA_EVENT_MQTT_ERROR\r\n");
            break;
        default:
            break;
    }
}
int main(void)
{

    board_init();
    if (0 != rfparam_init(0, NULL, 0)) {
        LOG_E("PHY RF init failed!\r\n");
        return 0;
    }
    lv_init();
    lv_port_disp_init();
    lv_port_indev_init();

    setup_ui(&guider_ui);
    custom_init(&guider_ui);
    events_init(&guider_ui);

    guider_ui.screen = 0;
    lv_log_register_print_cb(lv_log_print_g_cb);

    //lvgl 心跳任务
    xTaskCreate(lvgl_tick_task, (char*)"lvgl", 1024, NULL, 3, NULL);

    //内存打印任务
    // xTaskCreate(bl61x_show_heap_size_task, (char*)"heap", 1024, NULL, 4, NULL);

    //旋钮任务
    xTaskCreate(encoder_process_task, (char*)"encoder", 1024, (void*)&guider_ui, 5, (xTaskHandle*)&encoder_task);

    static char mac[6];
    homeAssistant_get_sta_mac(mac);

    homeassistant_blufi_init(NULL);
    xTaskCreate(device_state_task, "deivce", 1024*2, &guider_ui, 3, (TaskHandle_t*)&device_task);
    staWiFiInit();
    ha_device.name = "Knob灯板";
    ha_device.model = "Ai-M61-32S";
    ha_device.manufacturer = "Ai-Thinker";
    ha_device.hw_version = "v1.0";
    ha_device.sw_version = "v1.0";
    if (ha_device.mqtt_info.mqtt_clientID==NULL)
        ha_device.mqtt_info.mqtt_clientID = pvPortMalloc(128);

    memset(ha_device.mqtt_info.mqtt_clientID, 0, 128);
    sprintf(ha_device.mqtt_info.mqtt_clientID, "Ai-Triled-%02X%02X%02X%02X%02X%2X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    ha_device.mqtt_info.mqtt_username = "AiPi-Knob";
    ha_device.mqtt_info.mqtt_password = "12345678";
    ha_device.mqtt_info.mqtt_host = "192.168.32.2";
    ha_device.mqtt_info.port = 1883;
    ha_device.mqtt_info.mqtt_keeplive = 120;
    homeAssistant_device_init(&ha_device, ha_event_cb);

    vTaskStartScheduler();
    while (1) {
        LOG_F(" free heap size=%d", bl61x_get_heap_size());
        vTaskDelay(pdMS_TO_TICKS(3000));
    }
}


